# -*- coding: utf8 -*-
# help.py
"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes: must be tuple
* skip_sentinel: skip sentinel instance
* limit
* channels
* url
"""
import time
from core.ircfuncs import *
from util.functions import join_list
from core.optimizers import Dicts

#TODO
#afegir fn.channels[cur.channel]
def commands(bot, evt, cmd):
	""".commands"""
	print "commands()"
	cmds=[]
	for priority in bot.commands:
		for func in bot.commands[priority]:
			fn = bot.commands[priority][func]
			if fn.evttypes != ("msg", "notice", "action"):
				continue
			elif fn.name.endswith("_"):
				continue
			elif hasattr(fn, "showas"):
				cmds.append(fn.showas)
			elif isinstance(fn.rule[0], basestring):
				cmds.append(fn.rule[0])
			else:
				cmds.append(fn.name)
	print cmds
	cmds = ", ".join(cmds).split(", ")
	print "commands", cmds
	msg = ", ".join(sorted(cmds[:-1]))
	conj = bot._translate("and")
	msg += " %s %s" % (conj, cmds[-1])
	bot.reply(evt, "available commands: %s", msg)
commands.rule = "commands"
commands.aliases = ["cmds", "all"]
commands.chanlang = {"ca": "ordres", "es": "ordenes"}

def help(bot, evt, cmd):
	""".help[ <command>]"""
	if cmd.arguments:
		for p in bot.commands:
			for f in bot.commands[p]:
				fn = bot.commands[p][f]
				if isinstance(fn.rule, bool): fn.rule = [fn.rule] #todo: fix this bug!!!
				for s in fn.rule+fn.aliases+[fn.name]:
					if isinstance(s, basestring):
						if s == cmd.arguments:
							bot.reply(evt, fn.help)
							return
						elif hasattr(fn, "showas") and cmd.arguments in fn.showas.split(","):
							bot.reply(evt, fn.help)
							return
	else:
		link = bot._translate("help link")
		bot.reply(evt, "See %s", link)
help.rule = "help"
help.limit = 10

def aliases(bot, evt, cmd):
	"""aliases <command>"""
	fn_name = cmd.arguments
	found=False
	for prio in bot.commands:
		for fn in sorted(bot.commands[prio].keys()):
			if  isinstance(bot.commands[prio][fn].rule, list):
				for rule in bot.commands[prio][fn].rule:
					aliases_ = bot.commands[prio][fn].aliases
					print fn_name, rule, aliases_
					if rule == fn_name and not aliases_:
						bot.reply(evt, "command &B;%s&N; has no aliases" %(fn_name))
						found=True
					elif rule == fn_name:
						bot.reply(evt, "%s: %s" %(fn_name, join_list(aliases_, evt.lang)))
						found=True
					elif fn_name in bot.commands[prio][fn].aliases:
						bot.reply(evt, "%s: %s" %(rule, join_list(aliases_, evt.lang)))
						found=True
	if not found:
		bot.reply(evt, "no match for command")
aliases.rule="aliases"

def match_cmd(bot, evt, cmd):
	"""aliases <command>"""
	import types
	fn_name = cmd.arguments
	found=False
	for prio in bot.commands:
		for fn in sorted(bot.commands[prio]):
			if isinstance(bot.commands[prio][fn].rule, list):
				for rule in bot.commands[prio][fn].rule:
					fn = bot.commands[prio][fn]
					aliases_ = fn.aliases
					if rule == fn_name:
						bot.reply(evt, "&B;%s.py&N;: &o;%s()&N; | %s%s" %(fn.module, fn.name, fn_name, ". " + join_list(aliases_, evt.lang) if aliases_ else ""))
						found=True
					elif fn_name in bot.commands[prio][fn.name].aliases:
						bot.reply(evt, "&B;%s.py&N;: &o;%s()&N; | %s%s" %(fn.module, fn.name, rule, ", " + join_list(aliases_, evt.lang) if aliases_ else ""))
						found=True
					elif isinstance(rule, type(re.compile(""))) and fn_name == fn.name:
						bot.reply(evt, "&B;%s.py&N;: &o;%s()&N; | %s%s" %(fn.module, fn.name, "&t;regexp_type&N;", ", " + join_list(aliases_, evt.lang) if aliases_ else ""))
						found=True
	if not found:
		bot.reply(evt, "no match for command")
match_cmd.rule="wherecmd"
match_cmd.aliases="cmd"

def welcome(bot, evt, cmd):
	if evt.source != bot.current_nname and evt.chan != bot.defchan:
		#some clients join the channel and immediately quit network by changing host, and bot gives twice the welcome help.
		if not hasattr(bot, "whelp"): bot.whelp = time.time()-10
		if evt.chan == "##wikipedia-pt-bots" and time.time() - bot.whelp>1:
			bot.privmsg(evt.chan, u"Olá, $nick. Bem-vindo ao canal social da Wikipédia em Português. Se quiser fazer alguma consulta, escreva e espere até que possamos te responder.")
			bot.whelp = time.time()
		else:
			bot.choose_reply(evt, bot.replies.greeting, 15)
welcome.rule = ["join"]
welcome.evttypes = ("join",)

def format(string):
	string = string.split(" ")
	if string[0].lower() == "^none" and len(string)==1:
		return None
	elif string[0].lower() == "^true"and len(string)==1:
		return True
	elif string[0].lower() == "^false"and len(string)==1:
		return False
	string = " ".join(string)
	if re.search("^#(\d+)$", string):
		return int(re.sub("^#(\d+)$", r"\1", string))
	if re.search("^#(\d+\.\d+)$", string):
		return float(re.sub("^#(\d+\.\d+)$", r"\1", string))
	print __name__, "format", "%r" % string
	return string

def mnemo(bot, evt, cmd):
	""".def mnemo_key mnemo_value. - save menmo_value under mnemo_key to be used after prefixing underline char in a string"""
	if not has_access(bot, mnemo.level, evt): return True
	if cmd.action == "all":
		print bot.mnemo.keys()
		for word in bot.mnemo.keys():
			bot.reply(evt, "&B;%s:&N; %s", word, bot.mnemo[word])
		return True
	if (cmd.arguments  or cmd.opts["key"]) and cmd.action == "del":
		key = cmd.arguments or cmd.opts["key"]
		print "%r" % key
		word = bot.mnemo.delete(key)
		bot.reply(evt, "&r;deleted&N;: &B;%s:&N; %s", key, word)
		return True
	elif  cmd.arguments and cmd.action in ("modify", "change", "edit"):
		items = cmd.arguments.split(" ")
		key, value = items[0], " ".join(items[1:])
		updated = bot.mnemo.has_key(key)
		value = format(value)
		bot.mnemo.update(key, value)
		if updated:
			bot.reply(evt, "&l;updated&N;: &B;%s:&N; %s", key, value)
		else:
			bot.reply(evt, "&e;added&N;: &B;%s:&N; %s", key, value)
		return True
	elif  cmd.arguments and cmd.action == "append":
		items = cmd.arguments.split(" ")
		key, value = items[0], " ".join(items[1:])
		updated = bot.mnemo.has_key(key)
		if updated:
			value = "%s %s" % (bot.mnemo[key], value)
			bot.mnemo.update(key, value)
			bot.reply(evt, "&l;updated&N;: &B;%s:&N; %s", key, value)
		else:
			bot.reply(evt, "key &B;%s:&N; not found", key)
		return True
	elif  cmd.arguments and cmd.action == "prepend":
		items = cmd.arguments.split(" ")
		key, value = items[0], " ".join(items[1:])
		updated = bot.mnemo.has_key(key)
		if updated:
			value = "%s %s" % (value, bot.mnemo[key])
			bot.mnemo.update(key, value)
			bot.reply(evt, "&l;updated&N;: &B;%s:&N; %s", key, value)
		else:
			bot.reply(evt, "key &B;%s:&N; not found", key)
		return True
	if cmd.arguments:
		mnemonic = cmd.arguments.split(" ")
		if not bot.mnemo.has_key(mnemonic[0]):
			definition = format(" ".join(mnemonic[1:]))
			bot.reply(evt, "&B;%s:&N; %s", mnemonic[0], definition)
			bot.mnemo.update(mnemonic[0], definition)
		else:
			bot.reply(evt, "&B;%s:&N; %s", mnemonic[0], bot.mnemo[mnemonic[0]])
mnemo.rule = "def"
mnemo.level = "trusty"

def clap_(bot, evt, cmd):
	sentence = cmd.arguments
	if not sentence: return True
	for word in cmd.arguments.split(" "):
		if word.startswith("_") and bot.mnemo.has_key(word[1:]):
			sentence=re.sub(r"\b%s\b" % word, bot.mnemo[word[1:]], sentence)
	bot.reply(evt, sentence)
clap_.rule = "clap"
